package com.authenticateCenter.service.impl;

import com.authenticateCenter.domain.entity.Authority;
import com.authenticateCenter.domain.entity.Role;
import com.authenticateCenter.domain.entity.RoleAuthority;
import com.authenticateCenter.mapper.AuthorityMapper;
import com.authenticateCenter.mapper.RoleAuthorityMapper;
import com.authenticateCenter.mapper.RoleMapper;
import com.authenticateCenter.service.IRoleAuthorityService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 大忽悠
 * @since 2022年10月08日
 */
@Service
@RequiredArgsConstructor
public class RoleAuthorityServiceImpl extends ServiceImpl<RoleAuthorityMapper, RoleAuthority> implements IRoleAuthorityService {
    private final RoleAuthorityMapper roleAuthorityMapper;
    private final RoleMapper roleMapper;
    private final AuthorityMapper authorityMapper;

    /**
     * 发放前需判断角色和相关权限是否都存在,并且是否存在重复发放权限给某一个角色的问题
     * @param roleId
     * @param authorityIdList
     */
    @Override
    public void releaseAuthorityToRole(Integer roleId, List<Integer> authorityIdList) {
        Role.existCheckOfIdList(List.of(roleId),roleMapper);
        Authority.existCheck(authorityIdList,authorityMapper);
        Role.repeatReleaseCheck(roleId,authorityIdList,roleAuthorityMapper);
        authorityIdList.forEach(authorityId->{
            roleAuthorityMapper.insert(RoleAuthority.builder().rid(roleId).aid(authorityId).build());
        });
    }

    @Override
    public void revokeRoleOfAuthority(Integer roleId, List<Integer> authorityIdList) {
        authorityIdList.forEach(authorityId->{
            roleAuthorityMapper.delete(new QueryWrapper<RoleAuthority>()
                    .eq("rid",roleId).eq("aid",authorityId));
        });
    }
}
